package com.qf.fliter;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Base64Util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author AzureSky_X
 * @Date 2020/11/17 19:13
 * @Version 1.0
 */

@WebFilter(filterName = "AutoLoginFilter",value = "/login.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie c:cookies){
                if("autoLogin".equals(c.getName())){
                    String value = c.getValue();//加密之后字符串
                    //解密
                    String decode = Base64Util.decode(value);//zhangsan:123456
                    String[] split = decode.split(":");
                    String username=split[0];
                    String password=split[1];
                    UserService service=new UserServiceImpl();
                    User login = service.login(username, password);
                    if(login==null){
                        System.out.println("登陆失败");
                        chain.doFilter(req, resp);//资源放行
                        return;
                    }else{
                        System.out.println("登录成功");
                        request.getSession().setAttribute("loginUser",login);
                        response.sendRedirect(request.getContextPath()+"/good?action=getGoodsListByTypeId");
                        return;
                    }
                }
            }

            //如果for结束没有return出去，我们则判断没有存放autoLogin的cookie对象
            //此时资源放行到login.jsp
            chain.doFilter(req, resp);//资源放行
        }else{
            chain.doFilter(req, resp);//资源放行
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
